import hashlib
import requests
import time
import json
from util.logger import get_logger

logger = get_logger('搜图.log', __file__)


url = 'https://wallpaper.soutushenqi.com/v1/search/pcScreen'


# js逆向
def remove_empty_object(obj):
    """移除对象中的空值属性（对应JS的e.removeEmptyObject）"""
    if not isinstance(obj, dict):
        return obj
    new_obj = {}
    for k, v in obj.items():
        if v is None or v == "" or v == "undefined":
            continue
        new_obj[k] = remove_empty_object(v)
    return new_obj


def generate_sign(params, secret_key="d9fd3ec394"):
    """修正后：完全匹配JS的参数类型、处理逻辑"""
    # 1. 深拷贝并移除空值参数
    cleaned_params = remove_empty_object(json.loads(json.dumps(params)))

    # 2. 提取所有非对象类型的参数（JS中typeof y[T] != "object"），转为字符串（保留原始类型的字符串形式）
    sorted_items = []
    sorted_keys = sorted(cleaned_params.keys())  # 按键名升序排序
    for key in sorted_keys:
        value = cleaned_params[key]
        # JS中typeof判断：数组是object，所以过滤数组；其他非object类型保留
        if isinstance(value, (dict, list)):
            continue
        # 转为字符串（JS中任何值都会转成字符串，比如数字3→"3"）
        str_val = str(value)
        # 去除首尾空格（JS中O.toString().trim()）
        trimmed_val = str_val.strip() if str_val is not None else ""
        sorted_items.append((key, trimmed_val))

    # 3. 过滤空值参数（对应JS的filter函数）
    filtered_items = [(k, v) for k, v in sorted_items if v != ""]

    # 4. 序列化参数（JS的i.default.stringify，不编码）
    param_str = "&".join([f"{k}={v}" for k, v in filtered_items])

    # 5. 拼接密钥
    param_str_with_key = f"{param_str}&key={secret_key}"

    # 6. 计算MD5并大写
    md5 = hashlib.md5()
    md5.update(param_str_with_key.encode("utf-8"))
    sign = md5.hexdigest().upper()

    # 7. 合并sign到参数
    final_params = json.loads(json.dumps(params))
    final_params["sign"] = sign
    return json.dumps(final_params, indent=2, ensure_ascii=False)




for page in range(4):
    page = str(page)
    data = {
        'product_id': '52',
        'version_code': '29116',
        'sort_type': '0',
        'page': f'{page}',
        'search_word': '二次元',
    }
    result = generate_sign(data)
    print(result)
    response = requests.post(url, headers={
        'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3OTE4NTI0NDMsInByaW1hcnlLZXkiOiJ3YWxscGFwZXJfdG9rZW5fbmV4ZnMxSndfNTIifQ.2l9bA8jvrqjY6GBcvjtoltBwSKt7YhZavHPyhiFMK3E'
    }, data=result)
    logger.info(f'请求码：{response.status_code}')

    datas = response.json().get('data')
    for item in datas:
        time.sleep(1)
        img_url = item['largeUrl']
        img_id = item['id']

        logger.info(f'图片地址{img_url}')
        logger.info(f'图片id{img_id}')


        if img_url:
            logger.info("开始请求图片")
            res_img = requests.get(img_url, headers={
                'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36'
            })

            foot = res_img.headers['Content-Type'].split('/')[1]
            logger.info("开始保存图片")
            try:
                with open(f'./static/搜图神器/{img_id}.{foot}', 'wb') as f:
                    f.write(res_img.content)
                    logger.info("保存成功")
            except Exception as e:
                logger.error(e)

